﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Web.Routing;
using Sharp.Infrastructure;
using Sharp.Infrastructure.IoC;
using Sharp.Portal.Interface;
using Sharp.Portal.Mvc.Form;

namespace Sharp.Portal.Mvc
{
    /// <summary>
    /// 模板管理
    /// </summary>
    //[DebuggerStepThrough]
    public class TemplateManage
    {
        static readonly ConcurrentDictionary<string, string> ViewPathCache =
            new ConcurrentDictionary<string, string>();


        static TemplateManage()
        {
        }

        /// <summary>
        /// 获取模板
        /// </summary>
        /// <param name="requestContext"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string GetViewTemplate(RequestContext requestContext, object model)
        {
            var area = Convert.ToString(requestContext.RouteData.DataTokens["area"]);
            var controller = requestContext.RouteData.Values["Controller"].ToString();
            var action = requestContext.RouteData.Values["Action"].ToString();

            var isMobileDevice = false;//WebServer.IsMobileDevice();
            if (isMobileDevice)
            {
                return MobileHandle(model, area, controller, action);
            }
            else
            {
                return PCHandle(model, area, controller, action);
            }
        }

        private static string PCHandle(object model, string area, string controller, string action)
        {
            string key;
            if (area.IsNullOrEmpty())
            {
                key = $"GenerateCshtml{controller}_{action}";
            }
            else
            {
                key = $"GenerateCshtml{area}_{controller}_{action}";
            }
            ViewPathCache.TryGetValue(key, out var viewPath);//如果视图的缓存存在，说明Model没有修改。

            if (!string.IsNullOrEmpty(viewPath) && File.Exists(HttpContext.Current.Server.MapPath(viewPath)))
            {
                return viewPath;
            }



            lock (typeof(TemplateManage))
            {
                if (viewPath.IsNotNullOrEmpty() && File.Exists(HttpContext.Current.Server.MapPath(viewPath)))
                {
                    return viewPath;
                }

                if (area.IsNullOrEmpty())
                {
                    viewPath = $"~/Views/{controller}/{action}_Generate.cshtml";
                }
                else
                {
                    viewPath = $"~/Areas/{area}/Views/{controller}/{action}_Generate.cshtml";
                }

                var generateFile = new FileInfo(HttpContext.Current.Server.MapPath(viewPath));

                ITemplateProvider provider = null;
                if (model is ISharpForm)
                {
                    provider = (model as ISharpForm).UI.GetProvider();
                }
                else if (model is ISharpList)
                {
                    provider = (model as ISharpList).GetProvider();
                }

                string html = provider.GetTemplate(model, false);
                if (!generateFile.Directory.Exists)
                {
                    generateFile.Directory.Create();
                }
                if (generateFile.Exists)
                {
                    string viewHtml;
                    using (var sr = generateFile.OpenText())
                    {
                        viewHtml = sr.ReadToEnd();
                        sr.Close();
                    }

                    if (html == viewHtml)
                    {
                        return viewPath;
                    }
                }

                using (var objWriter = new StreamWriter(generateFile.FullName, false, Encoding.UTF8))
                {
                    objWriter.Write(html);
                    objWriter.Flush();
                    objWriter.Close();
                }


                ViewPathCache.TryAdd(key, viewPath);

                return viewPath;
            }
        }
        private static string MobileHandle(object model, string area, string controller, string action)
        {
            string key;
            if (area.IsNullOrEmpty())
            {
                key = $"GenerateMobileCshtml{controller}_{action}";
            }
            else
            {
                key = $"GenerateMobileCshtml{area}_{controller}_{action}";
            }
            ViewPathCache.TryGetValue(key, out var viewPath);//如果视图的缓存存在，说明Model没有修改。

            if (!string.IsNullOrEmpty(viewPath) && File.Exists(HttpContext.Current.Server.MapPath(viewPath)))
            {
                return viewPath;
            }

            lock (typeof(TemplateManage))
            {
                if (viewPath.IsNotNullOrEmpty() && File.Exists(HttpContext.Current.Server.MapPath(viewPath)))
                {
                    return viewPath;
                }

                if (area.IsNullOrEmpty())
                {
                    viewPath = $"~/Views/{controller}/{action}_MobileGenerate.cshtml";
                }
                else
                {
                    viewPath = $"~/Areas/{area}/Views/{controller}/{action}_MobileGenerate.cshtml";
                }

                var generateFile = new FileInfo(HttpContext.Current.Server.MapPath(viewPath));
                ITemplateProvider provider = null;
                if (model is ISharpForm)
                {
                    provider = (model as ISharpForm).UI.GetProvider();
                }
                else if (model is ISharpList)
                {
                    provider = (model as ISharpList).GetProvider();
                }
                string html = provider.GetTemplate(model, true);
                if (!generateFile.Directory.Exists)
                {
                    generateFile.Directory.Create();
                }
                if (generateFile.Exists)
                {
                    string viewHtml;
                    using (var sr = generateFile.OpenText())
                    {
                        viewHtml = sr.ReadToEnd();
                        sr.Close();
                    }

                    if (html == viewHtml)
                    {
                        return viewPath;
                    }
                }

                using (var objWriter = new StreamWriter(generateFile.FullName, false, Encoding.UTF8))
                {
                    objWriter.Write(html);
                    objWriter.Flush();
                    objWriter.Close();
                }


                ViewPathCache.TryAdd(key, viewPath);

                return viewPath;
            }
        }
    }
}
